package com.ttx.zookeeper.pubsub.curator;

import com.ttx.zookeeper.pubsub.curator.models.Instance;
import com.ttx.zookeeper.pubsub.curator.models.InstanceType;
import org.apache.curator.x.async.modeled.JacksonModelSerializer;
import org.apache.curator.x.async.modeled.ModelSpec;
import org.apache.curator.x.async.modeled.ModelSpecBuilder;
import org.apache.curator.x.async.modeled.ModeledFramework;
import org.apache.curator.x.async.modeled.typed.TypedModeledFramework;
import org.apache.zookeeper.CreateMode;

import java.util.concurrent.TimeUnit;

/**
 * @author TimFruit
 * @date 20-2-28 下午7:54
 */
public class Clients {
    /**
     * A client template for Instance instances
     */
    public static final TypedModeledFramework<Instance, InstanceType> instanceClient = TypedModeledFramework.from(
            ModeledFramework.builder(),
            builder(Instance.class),
            "/root/pubsub/instances/{instance-type}/{id}"
    );

    private static <T> ModelSpecBuilder<T> builder(Class<T> clazz) {
        return ModelSpec.builder(JacksonModelSerializer.build(clazz))
                // fixme 本人使用3.5.7测试创建ttl节点出现异常， 尚未测试成功， ttl节点是3.5版本出现的新功能, 很遗憾，没有测试成功
                // "org.apache.zookeeper.KeeperException$UnimplementedException: KeeperErrorCode = Unimplemented
                .withCreateMode(CreateMode.PERSISTENT_WITH_TTL)
                .withTtl(TimeUnit.MINUTES.toMillis(10)) // for our pub-sub example, messages are valid for 10 minutes
                ;
    }

    private Clients() {
    }
}
